package com.vincent.kdp.Activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.vincent.baseapp.util.CommonUtil;
import com.vincent.baseapp.util.SPUtil;
import com.vincent.kdp.R;
import com.vincent.kdp.http.RequestCallBack;
import com.vincent.kdp.repository.CheckGoodsRepository;
import com.vincent.kdp.ui.bean.response.AllGoodsOnCheckOutput;
import com.vincent.kdp.ui.bean.response.AllSimpleGoods;
import com.vincent.kdp.ui.bean.response.QueryRecordOutput;
import com.vincent.kdp.ui.bean.response.StartQueryOutput;
import com.vincent.kdp.ui.bean.response.UpdateCheckOutput;
import com.vincent.kdp.ui.other.UncheckGoodsListActivity;
import com.vincent.kdp.util.InventoryApi;
import com.vincent.kdp.util.StringToHex;
import com.vincent.kdp.util.UhfDev;
import com.vincent.kdp.view.CirclePercentView;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 盘货Activity
 */
public class CheckGoodsActivity extends Activity{


    @Bind(R.id.buttonStart)
    Button buttonStart;
    @Bind(R.id.buttonReStart)
    Button buttonReStart;
    @Bind(R.id.buttonUpdate)
    Button buttonUpdate;
    @Bind(R.id.circleView)
    CirclePercentView circleView;
    @Bind(R.id.textViewGoodsTotal)
    TextView textViewGoodsTotal;
    @Bind(R.id.textViewGoodshasChecked)
    TextView textViewGoodshasChecked;
    @Bind(R.id.unCheckDetailButton)
    Button unCheckDetailButton;
    @Bind(R.id.back_img)
    ImageView back;

    @Bind(R.id.textViewIp)
    TextView textViewIp;

    @Bind(R.id.toolbar_center_tv)
    TextView title;
    InventoryApi api;

    public Map<String,String> tagMap=new HashMap<String,String>();
    public Map<String,String> allGoodsMap=new HashMap<String,String>();

    private ProgressDialog progressDialog;

    private String allGoodsString="";

    private int curPercent=0;
    private int lastUpdatePercent=0;

    private Activity thisActivity;

    CheckGoodsRepository checkGoodsRepository=new CheckGoodsRepository();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_goods);
        ButterKnife.bind(this);
        thisActivity=this;
        repairCheckGoods();
        if(TextUtils.isEmpty(SPUtil.getString("differentTitle"))){
            title.setText("知己科技");
        }else{
            title.setText(SPUtil.getString("differentTitle"));
        }

    }

    private boolean connectUhf(){
        api=InventoryApi.instance(this);
        String ip=SPUtil.getString("UHF_IP");
        textViewIp.setText(ip);
        api.setIp(ip);
        String ret=api.connectReader();
        api.setHandleFuncAndCallback(msgHandler);
        Log.d("UHF_DEV",ret);
        if("0000".equals(ret)){
            return true;
        }else{
            CommonUtil.showToast(this,ret);
            return false;
        }
    }

    @OnClick({R.id.buttonStart,R.id.buttonUpdate,R.id.buttonReStart,R.id.unCheckDetailButton,R.id.back_img})
    @SuppressLint("SimpleDateFormat")
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonStart:
                startInventory();
                break;
            case R.id.buttonUpdate:
                checkUpdate();
                break;
            case R.id.buttonReStart:
                reStart();
                break;
            case R.id.unCheckDetailButton:
                gotoUnCheckGoods();
                break;
            case R.id.back_img:
                finish();
                break;
            default:
                break;
        }
    }

    private void gotoUnCheckGoods(){
        if(curPercent>0&&lastUpdatePercent!=curPercent){
            CommonUtil.showToast(this,"当前盘点还有未同步数据,请先更新");
        }else{
            Intent intent = new Intent(CheckGoodsActivity.this, UncheckGoodListActivity.class);
            startActivity(intent);
        }

    }

    private void startInventory(){
        String ret=api.connectReader();
        if("正在盘点".equals(buttonStart.getText())){
            buttonStart.setText("开始盘点");
            api.stopInventory();
        }else{
            buttonStart.setText("正在盘点");
            api.startInventory();
        }

    }
    private void reStart(){
        tagMap.clear();
        allGoodsMap.clear();
        SPUtil.remove("startQueryId");
        SPUtil.remove("allGoodsString");
        SPUtil.remove("hasCheckGoodsString");
        curPercent=0;
        repairCheckGoods();
    }
    private void checkUpdate(){
        if(lastUpdatePercent==curPercent) {
            CommonUtil.showToast(this, "当前盘点还有未同步数据,请先更新");
        }
        String hasCheckGoodsString=saveCheckCode();
        reqUpdateCheck(hasCheckGoodsString);
    }

    private void addToListView(final String epcCount) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                synchronized (CheckGoodsActivity.this){
                    String[] tagArr = epcCount.split(";");
                    String epc = tagArr[0];

                    if(epc.length()<26){
                        Log.w("EPC",epc+"的编码格式不正确,要求大于26位");
                        return;
                    }
                    String hex=epc.substring(0,26);
                    final String barCode= StringToHex.convertHexToString(hex);
                    if(!tagMap.containsKey(barCode)&&allGoodsMap.containsKey(barCode)){
                        tagMap.put(barCode,barCode);
                    }
                    calculatePercent();

                }
            }
        });
    }

    public String saveCheckCode(){
        StringBuffer hasCheckGoodsString=new StringBuffer();
        for(String v : tagMap.values()) {
           hasCheckGoodsString.append(v).append(",");
        }
        SPUtil.put("hasCheckGoodsString",hasCheckGoodsString);
        return hasCheckGoodsString.toString();
    }

    public void calculatePercent(){
        double allGoodsSize=allGoodsMap.size()+0.0;
        float num=0;
        if(allGoodsSize<=0){
            num=0;
        }else{
            num=((float)tagMap.size())/allGoodsMap.size();
        }

        textViewGoodsTotal.setText(allGoodsMap.size()+"个");
        textViewGoodshasChecked.setText(tagMap.size()+"个");
        Log.d("tagSize",tagMap.size()+"");
        Log.d("allGoodsSize",allGoodsSize+"");
        Log.d("CHECK_GOODS_PERCENT",num*100+"");
        Log.d("CHECK_GOODS_PERCENT",((int)(num*100))+"");
        int newPercent=(int)(num*100);
        if(newPercent>100){
            newPercent=100;
        }

        if(newPercent>=curPercent){
            circleView.setPercent(curPercent,newPercent);
            curPercent=newPercent;
        }
    }

    public Handler msgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String str = msg.getData().getString("msg");
            if ((null == str || 0 == str.length())
                    && ((UhfDev.MSG_TIMER != msg.what)
                    && (msg.what != UhfDev.MSG_PAUSE)
                    && (msg.what != UhfDev.MSG_RESUME)))
                return;
            if (msg.what == UhfDev.MSG_EPC) { // 标签内容
                String epc = str;
                addToListView(epc);
            } else if (msg.what == UhfDev.MSG_OPEN) { // 连接

            } else if (msg.what == UhfDev.MSG_TIMER) { // 定时器

            } else if (msg.what == UhfDev.MSG_PAUSE) { // 暂停
                api.stopInventory();
            } else if (msg.what == UhfDev.MSG_RESUME) { // 继续
                startInventory();
            } else { // 消息
            }
        }
    };

    private void exportCodeToMap(String codeString,Map map){
        if(codeString!=null){
            String barCode[]=codeString.split(",");
            if(barCode!=null&&barCode.length>0){
                for(String code:barCode){
                    if(code!=null&&!code.isEmpty()){
                        map.put(code,code);
                    }

                }
            }
        }
    }

    private void repairCheckGoods(){
        int startQueryId=SPUtil.getInt("startQueryId");
        System.out.println("startQueryId"+startQueryId);


        checkGoodsRepository.reqGetRecordById(startQueryId, new RequestCallBack<QueryRecordOutput>() {
            @Override
            public void onSuccess(QueryRecordOutput object) {
                if(object.getData().getStatus()==0&&object.getData().getId()>0){
                    String allGoodsString= SPUtil.getString("allGoodsString");
                    exportCodeToMap(allGoodsString,allGoodsMap);
                    String hasCheckGoodsString= SPUtil.getString("hasCheckGoodsString");
                    exportCodeToMap(hasCheckGoodsString,tagMap);
                    calculatePercent();
                    lastUpdatePercent=curPercent;
                    connectUhf();
                }else{
                    initCheck();
                }
            }

            @Override
            public void onFalse(String msg) {
                initCheck();
            }
        });

    }

    public void initCheck(){
        connectUhf();
        reqStartQuery();
        reqGetGoodsOnShelf();
        calculatePercent();
    }



    public void dialog(String msg){
        AlertDialog.Builder builder = new AlertDialog.Builder(CheckGoodsActivity.this);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    public void reqUpdateCheck(String hasCheckGoodsString){
        int checkId=SPUtil.getInt("startQueryId");
        checkGoodsRepository.reqUpdateCheck(hasCheckGoodsString,checkId,new RequestCallBack<UpdateCheckOutput>(){
            @Override
            public void onSuccess(UpdateCheckOutput object) {
                if(object.getCode()==0){
                    lastUpdatePercent=curPercent;
                    dialog("更新盘点数据:成功");
                }else{
                    dialog("更新盘点数据:失败");
                }
            }

            @Override
            public void onFalse(String msg) {
                dialog("更新盘点数据:请求服务器异常");
            }
        });
    }


    /**
     * 开始一次新的盘货
     */
    public void reqStartQuery(){
        checkGoodsRepository.reqStartQuery(new RequestCallBack<StartQueryOutput>(){
            @Override
            public void onSuccess(StartQueryOutput object) {
                if(object.getCode()==0){
                    SPUtil.put("startQueryId",object.getData());
                    SPUtil.put("startQueryTime",new Date().getTime());
                }else{
                    dialog("重新盘点:失败");
                }
            }

            @Override
            public void onFalse(String msg) {
                dialog("重新盘点:请求服务器异常");
            }
        });
    }

    public void reqGetGoodsOnShelf(){
        progressDialog = ProgressDialog.show(CheckGoodsActivity.this, "正在加载", "请稍候", true, false);
        checkGoodsRepository.reqGetGoodsOnShelf(new RequestCallBack<AllGoodsOnCheckOutput>(){
            @Override
            public void onSuccess(AllGoodsOnCheckOutput object) {
                List<AllSimpleGoods> list=object.getData();
                StringBuffer sb=new StringBuffer();
                for(int i=0;i<list.size();i++){
                    String barCode=list.get(i).getBarCode();
                    sb.append(list.get(i).getBarCode()).append(",");
                    allGoodsMap.put(barCode,barCode);
                }
                allGoodsString=sb.toString();
                Log.d("CHECK_GOODS",allGoodsString);
                SPUtil.put("allGoodsString",allGoodsString);
                progressDialog.dismiss();
            }

            @Override
            public void onFalse(String msg) {
                progressDialog.dismiss();
            }
        });
    }
}
